<?php
namespace Mobile\Controller;
use \Think\Log;

class ExchangeController extends MobileController {
    /**
    * 兑换记录
    *     
    * @param mixed $p 页码
    * @param mixed $startdate 起始日期
    * @param mixed $enddate 结束日期
    */
    public function logs($p=1,$limit=10,$status='',$startdate='',$enddate=''){
        if(empty($this->uid)){
            $this->err('用户未登录!');
        }
        
        //获取兑换历史记录
        unset($where);
        $where['uid'] = $this->uid;
        if(empty($startdate)){
            if(empty($enddate)){
                
            }else{
                $enddate = date('Y-m-d',24*60*60 + strtotime($enddate));
                $where['posttime'] = array('between',array($startdate,$enddate));
            }
        }else{
            if(empty($enddate)){
                
            }else{
                $enddate = date('Y-m-d',24*60*60 + strtotime($enddate));
                $where['posttime'] = array('elt',$enddate);
            }
        }
        if(!empty($status)){
            $where['status'] = $status;
        }
        $modelLog = M('UserExchange');
        
        $count = $modelLog->where($where)->count();
        $resLog = $modelLog->where($where)->order('eid DESC')->page("$p,$limit")->select();
        $model = M('Document');
        $status = array(-1=>'订单已取消',0=>'订单已生成',1=>'订单已审核',2=>'订单已完成');
        foreach($resLog as &$row){
            $resGood = $model->where('id='.$row['goods_id'])->cache()->find();
            if($resGood){
                $row['goods_name'] = $resGood['title'];
            }
            foreach($status as $key => $value){
                if($key == $row['status']){
                    $row['status_text'] = $value;
                    break;
                }
            }
            unset($row['uid']);
        }
        $ret = array(
            'count' => $count,
            'data' => $resLog,
        );
        $this->succ($ret);
   }

   /**
   * 获取可兑换商品列表
   *    
   * @param mixed $ptype 商品类别
   */
   public function goods($ptype=1){
        if(empty($this->uid)){
            $this->err('用户未登录!');
        }
        
        //获取商品类别
        $category = $this->category('goods');
              
        $modelDocument = D('Document');
        $list = $modelDocument->lists($category['id']);
        
        $ret = array();
        //因为价格等信息在扩展表中，所以得获取详情
        foreach($list as &$row){
            $data = $modelDocument->detail($row['id']);
            if($data['ptype'] == $ptype){
                $ret[] = array(
                    'id' => $row['id'],
                    'title' => $data['title'],
                    'ptype' => $data['ptype'],
                    'description' =>$data['description'],
                    'price' => $data['price'],
                    'content' => U('Detail/index',array('id'=>$row['id']),true,true),
                    'picurl' => $this->getFullUrl(get_cover($data['cover_id'],'path')),
                );
            }
        }
        $this->succ($ret);
   }
   
    
    /**
    * 支出金额
    * 
    * @param mixed $money 金额
    * @param mixed $memo 备注
    */
    protected function pay($money,$memo){
        if(empty($this->uid)){
            return;
        }
        if($this->uid){
            $where['uid'] = $this->uid;
            $where['status'] = array('egt',2);
            $modelOrder = M('Order');
            $modelOrderAmtLog = M('OrderAmtLog');
            M()->startTrans();
            $resOrder = $modelOrder->where($where)->select();
            foreach($resOrder as $row){
                $n_amt = $row['n_amt'];
                if($n_amt>=$money){//如果金额够用了
                    unset($data);
                    $data['order_id'] = $row['order_id'];
                    $data['pdate'] = date('Y-m-d H:i:s');
                    $data['isfrozen'] = 0;
                    $data['ptype'] = -1;
                    $data['initval'] = $n_amt;
                    $data['chgval'] = -$money;
                    $data['endval'] = $n_amt - $money;
                    $data['memo'] = $memo;
                    $modelOrderAmtLog->add($data);
                    
                    unset($data);
                    $data['n_amt'] = $n_amt - $money;
                    $modelOrder->where('order_id='.$row['order_id'])->save($data);
                    
                    break;
                }else{ //如果不够用
                    unset($data);
                    $data['order_id'] = $row['order_id'];
                    $data['pdate'] = date('Y-m-d H:i:s');
                    $data['isfrozen'] = 0;
                    $data['ptype'] = -1;
                    $data['initval'] = $n_amt;
                    $data['chgval'] = -$n_amt;
                    $data['endval'] = 0;
                    $data['memo'] = $memo ."(扣减部分 $n_amt)";
                    $modelOrderAmtLog->add($data);
                    
                    unset($data);
                    $data['n_amt'] = 0;
                    $modelOrder->where('order_id='.$row['order_id'])->save($data);
                    
                    $money -= $n_amt;                    
                }
            }
            M()->commit();
        }
    }
    
    /**
    * 开启兑换
    * 
    */
    public function buy(){
        if(empty($this->uid)){
            $this->err('用户未登录!');
        }

        $uid = $this->uid;
        $goods_id = I('good_id');
        $extdata = I('extdata');
        $num = I('num');
        $encrypt_pass = I('cashpass');
        $cashpass = $this->decrypt($encrypt_pass);
        
        empty($goods_id) && $this->err('商品未选择');
        empty($extdata) && $this->err('信息不完整');
        empty($num) && $this->err('数量不正确');
        empty($cashpass) && $this->err('请输入支付密码');
        
        $modelMember = M('Member');
        $pass = $modelMember->where("uid=$uid")->getField('cash_passwd');
        if(think_md5($cashpass,C('DATA_AUTH_KEY'))!=$pass){
            $this->err('支付密码错误！');
        }
        
        $modelDocument = D('Document');
        $info = $modelDocument->detail($goods_id);
        $price = $info['price'];
        
        $amt = $price * $num;
        
        //获取用户可兑换金额
        $modelOrder = M('Order');
        $where['uid'] = $uid;
        $where['status'] = array('egt',2);
        $totalMoney = $modelOrder->where($where)->sum('n_amt');
        
        if($amt>$totalMoney) $this->error('没有足够的可用金额');
        
        $memo = "兑换{$info['title']},{$price}*{$num}={$amt}";
        $this->pay($amt,$memo);

        //记录兑换记录
        $modelLog = M('UserExchange');
        unset($data);
        $data['uid'] = $uid;
        $data['goods_id'] = $goods_id;
        $data['price'] = $price;
        $data['num'] = $num;
        $data['extdata'] = $extdata;
        $modelLog->add($data);
        
        //重新统计可用金额
        $totalMoney = $modelOrder->where($where)->sum('n_amt');
        
        $ret = array(
            'total_money'=>$totalMoney,
        );
        $this->success($ret);
    }
   
   
    private function category($id = 0){
        /* 标识正确性检测 */
        $id = $id ? $id : I('get.category', 0);
        if(empty($id)){
            $this->error('没有指定文档分类！');
        }

        /* 获取分类信息 */
        $category = D('Category')->info($id);
        if($category && 1 == $category['status']){
            switch ($category['display']) {
                case 0:
                    $this->error('该分类禁止显示！');
                    break;
                //TODO: 更多分类显示状态判断
                default:
                    return $category;
            }
        } else {
            $this->error('分类不存在或被禁用！');
        }
    }
    
}